import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { FileItem, FileForm } from '@/types'
import { useUserStore } from './user'

export const useFileStore = defineStore('file', () => {
  const files = ref<FileItem[]>([
    // 根目录文件夹
    {
      id: 1,
      name: '项目文档',
      type: 'folder',
      path: '/项目文档',
      uploadTime: '2024-01-01 10:00:00',
      uploader: '张经理',
      uploaderId: 2,
      description: '项目相关文档存储',
      tags: ['项目', '文档'],
      category: 'other',
      isPublic: true,
      downloadCount: 0,
      updateTime: '2024-01-01 10:00:00',
      folderType: 'public',
      canUpload: true,
      canDownload: true,
      canManage: true
    },
    {
      id: 2,
      name: 'JSA模板',
      type: 'folder',
      path: '/JSA模板',
      uploadTime: '2024-01-01 10:00:00',
      uploader: '李工程师',
      uploaderId: 3,
      description: 'JSA模板文件存储',
      tags: ['JSA', '模板'],
      category: 'other',
      isPublic: true,
      downloadCount: 0,
      updateTime: '2024-01-01 10:00:00',
      folderType: 'public',
      canUpload: true,
      canDownload: true,
      canManage: true
    },
    {
      id: 3,
      name: '安全培训资料',
      type: 'folder',
      path: '/安全培训资料',
      uploadTime: '2024-01-01 10:00:00',
      uploader: '刘监督',
      uploaderId: 5,
      description: '安全培训相关文件',
      tags: ['安全', '培训'],
      category: 'other',
      isPublic: true,
      downloadCount: 0,
      updateTime: '2024-01-01 10:00:00',
      folderType: 'public',
      canUpload: true,
      canDownload: true,
      canManage: true
    },
    {
      id: 11,
      name: '我的文档',
      type: 'folder',
      path: '/我的文档',
      uploadTime: '2024-01-01 10:00:00',
      uploader: '当前用户',
      uploaderId: 1,
      description: '个人文档存储',
      tags: ['个人', '文档'],
      category: 'other',
      isPublic: false,
      downloadCount: 0,
      updateTime: '2024-01-01 10:00:00',
      folderType: 'private',
      ownerId: 1,
      canUpload: true,
      canDownload: true,
      canManage: true
    },
    
    // 文件
    {
      id: 4,
      name: '项目启动计划书.pdf',
      type: 'file',
      size: 2048576, // 2MB
      extension: 'pdf',
      path: '/项目文档/项目启动计划书.pdf',
      parentId: 1,
      uploadTime: '2024-01-02 09:30:00',
      uploader: '张经理',
      uploaderId: 2,
      description: '2024年项目启动计划书',
      tags: ['项目', '计划书', 'PDF'],
      category: 'document',
      isPublic: true,
      downloadCount: 15,
      updateTime: '2024-01-02 09:30:00'
    },
    {
      id: 5,
      name: 'JSA作业安全分析模板.xlsx',
      type: 'file',
      size: 512000, // 500KB
      extension: 'xlsx',
      path: '/JSA模板/JSA作业安全分析模板.xlsx',
      parentId: 2,
      uploadTime: '2024-01-03 14:20:00',
      uploader: '李工程师',
      uploaderId: 3,
      description: '标准JSA分析表格模板',
      tags: ['JSA', '模板', 'Excel'],
      category: 'document',
      isPublic: true,
      downloadCount: 32,
      updateTime: '2024-01-03 14:20:00'
    },
    {
      id: 6,
      name: '安全培训视频.mp4',
      type: 'file',
      size: 52428800, // 50MB
      extension: 'mp4',
      path: '/安全培训资料/安全培训视频.mp4',
      parentId: 3,
      uploadTime: '2024-01-04 16:45:00',
      uploader: '刘监督',
      uploaderId: 5,
      description: '新员工安全培训视频',
      tags: ['安全', '培训', '视频'],
      category: 'video',
      isPublic: true,
      downloadCount: 8,
      updateTime: '2024-01-04 16:45:00'
    },
    {
      id: 7,
      name: '设备检查报告.docx',
      type: 'file',
      size: 1024000, // 1MB
      extension: 'docx',
      path: '/项目文档/设备检查报告.docx',
      parentId: 1,
      uploadTime: '2024-01-05 11:15:00',
      uploader: '王主任',
      uploaderId: 4,
      description: '本月设备检查报告',
      tags: ['设备', '检查', '报告'],
      category: 'document',
      isPublic: false,
      downloadCount: 3,
      updateTime: '2024-01-05 11:15:00'
    },
    {
      id: 8,
      name: '工作现场照片.jpg',
      type: 'file',
      size: 3072000, // 3MB
      extension: 'jpg',
      path: '/项目文档/工作现场照片.jpg',
      parentId: 1,
      uploadTime: '2024-01-06 13:30:00',
      uploader: '赵师傅',
      uploaderId: 6,
      description: '工作现场环境照片',
      tags: ['现场', '照片'],
      category: 'image',
      isPublic: true,
      downloadCount: 12,
      updateTime: '2024-01-06 13:30:00'
    },
    {
      id: 9,
      name: '应急预案.pdf',
      type: 'file',
      size: 1536000, // 1.5MB
      extension: 'pdf',
      path: '/安全培训资料/应急预案.pdf',
      parentId: 3,
      uploadTime: '2024-01-07 08:20:00',
      uploader: '刘监督',
      uploaderId: 5,
      description: '紧急情况应急预案',
      tags: ['应急预案', '安全'],
      category: 'document',
      isPublic: true,
      downloadCount: 25,
      updateTime: '2024-01-07 08:20:00'
    },
    {
      id: 10,
      name: '承包商资质证书.pdf',
      type: 'file',
      size: 2560000, // 2.5MB
      extension: 'pdf',
      path: '/承包商资质证书.pdf',
      uploadTime: '2024-01-08 15:10:00',
      uploader: '张经理',
      uploaderId: 2,
      description: '承包商资质证书扫描件',
      tags: ['承包商', '资质', '证书'],
      category: 'document',
      isPublic: false,
      downloadCount: 2,
      updateTime: '2024-01-08 15:10:00'
    }
  ])

  // 获取所有文件
  const getAllFiles = () => {
    return Promise.resolve(files.value)
  }

  // 根据ID获取文件
  const getFileById = (id: number) => {
    const file = files.value.find(f => f.id === id)
    return Promise.resolve(file)
  }

  // 根据父目录获取文件列表
  const getFilesByParentId = (parentId?: number) => {
    const filtered = files.value.filter(f => f.parentId === parentId)
    return Promise.resolve(filtered)
  }

  // 创建文件/文件夹
  const createFile = (form: FileForm) => {
    const newFile: FileItem = {
      id: Math.max(...files.value.map(f => f.id)) + 1,
      size: form.type === 'file' ? Math.floor(Math.random() * 10000000) : undefined, // 随机文件大小
      extension: form.type === 'file' ? form.name.split('.').pop() : undefined,
      path: form.parentId ? 
        `${files.value.find(f => f.id === form.parentId)?.path}/${form.name}` : 
        `/${form.name}`,
      uploadTime: new Date().toLocaleString(),
      uploader: '当前用户',
      uploaderId: 1,
      downloadCount: 0,
      updateTime: new Date().toLocaleString(),
      ...form
    }
    files.value.push(newFile)
    return Promise.resolve(newFile)
  }

  // 更新文件/文件夹
  const updateFile = (id: number, form: Partial<FileForm>) => {
    const index = files.value.findIndex(f => f.id === id)
    if (index !== -1) {
      files.value[index] = {
        ...files.value[index],
        ...form,
        updateTime: new Date().toLocaleString()
      }
      return Promise.resolve(files.value[index])
    }
    return Promise.reject(new Error('文件不存在'))
  }

  // 删除文件/文件夹
  const deleteFile = (id: number) => {
    const index = files.value.findIndex(f => f.id === id)
    if (index !== -1) {
      // 如果是文件夹，同时删除子文件
      const deleteChildren = (parentId: number) => {
        const children = files.value.filter(f => f.parentId === parentId)
        children.forEach(child => {
          deleteChildren(child.id)
          const childIndex = files.value.findIndex(f => f.id === child.id)
          if (childIndex !== -1) {
            files.value.splice(childIndex, 1)
          }
        })
      }
      
      deleteChildren(id)
      files.value.splice(index, 1)
      return Promise.resolve(true)
    }
    return Promise.reject(new Error('文件不存在'))
  }

  // 根据分类获取文件
  const getFilesByCategory = (category: string) => {
    const filtered = files.value.filter(f => f.category === category)
    return Promise.resolve(filtered)
  }

  // 根据标签获取文件
  const getFilesByTag = (tag: string) => {
    const filtered = files.value.filter(f => f.tags.includes(tag))
    return Promise.resolve(filtered)
  }

  // 搜索文件
  const searchFiles = (keyword: string) => {
    const filtered = files.value.filter(f => 
      f.name.includes(keyword) || 
      f.description?.includes(keyword) ||
      f.tags.some(tag => tag.includes(keyword))
    )
    return Promise.resolve(filtered)
  }

  // 获取文件树结构
  const getFileTree = () => {
    const buildTree = (parentId?: number): FileItem[] => {
      return files.value
        .filter(f => f.parentId === parentId)
        .map(f => ({
          ...f,
          children: buildTree(f.id)
        }))
    }
    return Promise.resolve(buildTree())
  }

  // 增加下载次数
  const incrementDownloadCount = (id: number) => {
    const file = files.value.find(f => f.id === id)
    if (file) {
      file.downloadCount++
      return Promise.resolve(file.downloadCount)
    }
    return Promise.reject(new Error('文件不存在'))
  }

  // 权限检查方法
  const checkFolderPermission = (folderId: number, action: 'upload' | 'download' | 'manage') => {
    const userStore = useUserStore()
    const currentUser = userStore.user
    const folder = files.value.find(f => f.id === folderId)
    
    if (!folder || folder.type !== 'folder') {
      return false
    }

    // 管理员拥有所有权限
    if (currentUser?.roles.includes('admin')) {
      return true
    }

    // 公开文件夹权限检查
    if (folder.folderType === 'public') {
      if (action === 'upload' || action === 'download') {
        // 公开文件夹只有管理员可以上传下载
        return false
      }
      if (action === 'manage') {
        // 公开文件夹只有管理员可以管理
        return false
      }
    }

    // 私有文件夹权限检查
    if (folder.folderType === 'private') {
      if (folder.ownerId === currentUser?.id) {
        // 文件夹所有者拥有所有权限
        return true
      } else {
        // 非所有者无权限
        return false
      }
    }

    return false
  }

  // 获取用户可访问的文件夹列表
  const getAccessibleFolders = () => {
    const userStore = useUserStore()
    const currentUser = userStore.user
    
    if (!currentUser) {
      return Promise.resolve([])
    }

    // 管理员可以看到所有文件夹
    if (currentUser.roles.includes('admin')) {
      return Promise.resolve(files.value.filter(f => f.type === 'folder'))
    }

    // 普通用户只能看到自己创建的私有文件夹
    const accessibleFolders = files.value.filter(f => 
      f.type === 'folder' && 
      (f.folderType === 'private' && f.ownerId === currentUser.id)
    )

    return Promise.resolve(accessibleFolders)
  }

  // 检查文件操作权限
  const checkFilePermission = (fileId: number, action: 'download' | 'delete') => {
    const userStore = useUserStore()
    const currentUser = userStore.user
    const file = files.value.find(f => f.id === fileId)
    
    if (!file) {
      return false
    }

    // 管理员拥有所有权限
    if (currentUser?.roles.includes('admin')) {
      return true
    }

    // 公开文件夹中的文件权限检查
    if (file.parentId) {
      const parentFolder = files.value.find(f => f.id === file.parentId)
      if (parentFolder?.folderType === 'public') {
        // 公开文件夹中的文件只有管理员可以操作
        return false
      }
    }

    // 私有文件夹中的文件权限检查
    if (file.parentId) {
      const parentFolder = files.value.find(f => f.id === file.parentId)
      if (parentFolder?.folderType === 'private') {
        // 只有文件夹所有者可以操作其中的文件
        return parentFolder.ownerId === currentUser?.id
      }
    }

    // 根目录文件的权限检查
    if (!file.parentId) {
      // 根目录文件只有管理员可以操作
      return false
    }

    return false
  }

  return {
    files,
    getAllFiles,
    getFileById,
    getFilesByParentId,
    createFile,
    updateFile,
    deleteFile,
    getFilesByCategory,
    getFilesByTag,
    searchFiles,
    getFileTree,
    incrementDownloadCount,
    checkFolderPermission,
    getAccessibleFolders,
    checkFilePermission
  }
})
